/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controleur;

import application.Facade;
import application.beans.CompteBean;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Étienne
 */
public class ServLogin extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{
        response.setContentType("text/html;charset=UTF-8");
        HttpSession session = request.getSession();
        
        Facade f = new Facade();
        
        String username = request.getParameter(ConstantesWeb.PARAM_USERNAME);
        String password = request.getParameter(ConstantesWeb.PARAM_PASSWORD);
        String next = request.getParameter(ConstantesWeb.PARAM_NEXT);
        Boolean valide = false;
        CompteBean compte = null;
        
        // Si la page suivante est vide, on met la page d'accueil
        if(next == null || next.equals("")){next = ConstantesWeb.ATTRIBUT_SERV_ACCUEIL;}
        
        // On vérifie si le username ou le password est null
        if(username != null || password != null){
            if(!(username.replace(" ", "").equals("")) || !(password.replace(" ", "").equals(""))){
                // On encrypte le mot de passe
                try {
                    MessageDigest md = MessageDigest.getInstance("MD5"); 
                    byte[] messageDigest = md.digest(password.getBytes());  
                    BigInteger number = new BigInteger(1, messageDigest);   
                    String hashtext = number.toString(16);         
                    // Now we need to zero pad it if you actually want the full 32 chars.   
                    while (hashtext.length() < 32) {         
                        hashtext = "0" + hashtext;          
                    }       
                    password = hashtext;
                } catch (NoSuchAlgorithmException ex) {
                    Logger.getLogger(ServLogin.class.getName()).log(Level.SEVERE, null, ex);
                }

                // On va chercher s'il y a un compte avec ce nom d'utilisateur
                compte = f.chercherCompteUsername(username);
                if(compte != null && compte.getActif().equals("O")){
                    valide = f.verifierPassword(compte.getIdCompte(), password);
                }
            }
            // Si le tout est valide, on met le compte dans la session
            if(valide){
                session.setAttribute(ConstantesWeb.ATTRIBUT_UTILISATEUR, compte);
            }
            else{
                // On met le message d'erreur de login
                session.setAttribute(ConstantesWeb.ATTRIBUT_ERREUR_LOGIN, "Compte invalide.");
            }
        }
        
        RequestDispatcher rd = getServletContext().getRequestDispatcher(next);
        rd.forward(request, response);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
